/**
 * 质量评分服务
 * 用于评估生成内容的质量
 */

export interface QualityScoreRequest {
  content: string;
  scenario?: 'general' | 'academic' | 'creative' | 'technical' | 'news';
  language?: string;
  reference?: string;
}

export interface QualityScoreResponse {
  overall_score: number;
  dimensions: {
    coherence: number;
    relevance: number;
    completeness: number;
    clarity: number;
    originality: number;
    factuality: number;
  };
  suggestions: string[];
  confidence: number;
  timestamp: string;
}

export interface OriginalityCheckRequest {
  content: string;
  check_internet?: boolean;
  check_database?: boolean;
}

export interface OriginalityCheckResponse {
  originality_score: number;
  similarity_results: Array<{
    source: string;
    similarity: number;
    matched_content: string;
  }>;
  is_original: boolean;
  confidence: number;
}

class QualityService {
  private baseUrl: string;

  constructor() {
    this.baseUrl = import.meta.env.VITE_API_URL || 'http://localhost:8002/api/v1';
  }

  /**
   * 评估内容质量
   */
  async evaluateQuality(request: QualityScoreRequest): Promise<QualityScoreResponse> {
    try {
      const response = await fetch(`${this.baseUrl}/quality/score`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify({
          content: request.content,
          scenario: request.scenario || 'general',
          language: request.language || 'zh',
          reference: request.reference
        })
      });

      if (!response.ok) {
        throw new Error(`Quality evaluation failed: ${response.statusText}`);
      }

      return await response.json();
    } catch (error) {
      console.error('Quality evaluation error:', error);
      throw error;
    }
  }

  /**
   * 批量评估内容质量
   */
  async evaluateBatch(contents: string[]): Promise<QualityScoreResponse[]> {
    try {
      const response = await fetch(`${this.baseUrl}/quality/batch-score`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify({
          contents: contents,
          scenario: 'general',
          language: 'zh'
        })
      });

      if (!response.ok) {
        throw new Error(`Batch quality evaluation failed: ${response.statusText}`);
      }

      const result = await response.json();
      return result.results;
    } catch (error) {
      console.error('Batch quality evaluation error:', error);
      throw error;
    }
  }

  /**
   * 检查内容原创性
   */
  async checkOriginality(request: OriginalityCheckRequest): Promise<OriginalityCheckResponse> {
    try {
      const response = await fetch(`${this.baseUrl}/originality/check`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify({
          content: request.content,
          check_internet: request.check_internet ?? true,
          check_database: request.check_database ?? true
        })
      });

      if (!response.ok) {
        throw new Error(`Originality check failed: ${response.statusText}`);
      }

      return await response.json();
    } catch (error) {
      console.error('Originality check error:', error);
      throw error;
    }
  }

  /**
   * 获取质量评分历史
   */
  async getScoreHistory(contentId?: string, limit: number = 10): Promise<any[]> {
    try {
      const params = new URLSearchParams({
        limit: limit.toString()
      });

      if (contentId) {
        params.append('content_id', contentId);
      }

      const response = await fetch(`${this.baseUrl}/quality/history?${params}`, {
        headers: {
          'Authorization': `Bearer ${this.getAuthToken()}`
        }
      });

      if (!response.ok) {
        throw new Error(`Failed to get score history: ${response.statusText}`);
      }

      return await response.json();
    } catch (error) {
      console.error('Get score history error:', error);
      throw error;
    }
  }

  /**
   * 获取质量改进建议
   */
  async getImprovementSuggestions(content: string, score: number): Promise<string[]> {
    try {
      const response = await fetch(`${this.baseUrl}/quality/suggestions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify({
          content: content,
          current_score: score
        })
      });

      if (!response.ok) {
        throw new Error(`Failed to get suggestions: ${response.statusText}`);
      }

      const result = await response.json();
      return result.suggestions;
    } catch (error) {
      console.error('Get suggestions error:', error);
      return [];
    }
  }

  /**
   * 获取认证令牌
   */
  private getAuthToken(): string {
    return localStorage.getItem('auth_token') || '';
  }
}

export const qualityService = new QualityService();